package com.wing.api.add.department.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wing.api.ApplicationContextUtil;
import com.wing.api.add.department.BaseDepartmentService;
import com.wing.cabinet.model.response.EnterpricceIdVO;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.DepartmentForm;
import com.wing.user.model.response.CompanyInfoVO;
import com.wing.user.model.response.DepartmentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * 标准部门接口
 */
@Service
@Slf4j
public class StandardDepartmentServiceImpl implements BaseDepartmentService {

    @Transactional
    @Override
    public void logicProcess(JSONObject jsonObject, EnterpricceIdVO enterpricceIdVo) throws IOException {
        log.info("请求参数,{}", jsonObject.toJSONString());
        //此处需要做接口签名验证
        //sign = md5（参数1+参数2+参数3+key）
        String sourceSign = jsonObject.getString("sign"); // 签名值
        JSONArray data = jsonObject.getJSONArray("data"); //业务数据
        if(StringUtils.isBlank(sourceSign)){
            throw new BusinessException("签名值为空！");
        }
        if(StringUtils.isBlank(data.toJSONString())){
            throw new BusinessException("请求参数为空！");
        }

        /*log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex("companyName" + "parentName" +"code" + "departmentName" + enterpricceIdVo.getKey());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }*/

        StringBuffer tempStr = new StringBuffer();
        tempStr.append(data);
        tempStr.append(enterpricceIdVo.getKey());
        log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex(tempStr.toString());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }
        UserClient userClient = (UserClient) ApplicationContextUtil.getBean("userClientFallback");
        System.out.println(userClient);
        //业务逻辑
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObj = data.getJSONObject(i);
            String companyName = jsonObj.getString("companyName");
            if(StringUtils.isEmpty(companyName)){
                throw new BusinessException("第" + (i+1) +  "行企业名称不能为空！");
            }
            JsonResult<CompanyInfoVO> companyJsonResult = userClient.getCompanyByName(companyName);
            if(companyJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) +companyName + "行不存在，请先同步企业数据！");
            }
            String parentName = jsonObj.getString("parentName");
            JsonResult<DepartmentVO> departmentJsonResult = null;
            if(StringUtils.isNotBlank(parentName)){
                 departmentJsonResult = userClient.getDepartmentByName(parentName,null,null);
                if(departmentJsonResult.getData().getId() == null){
                    throw new BusinessException("第" + (i+1)+"行" + parentName + "该上级部门数据不存在！");
                }
            }

            String code = jsonObj.getString("code");
            if(StringUtils.isEmpty(code)){
                throw new BusinessException("第" + (i+1) +  "行编码不能为空！");
            }
            JsonResult userClientOnly = userClient.isOnly(code, null);
            if("false".equals(userClientOnly.getData().toString())){
                throw new BusinessException("第" + (i+1) +"行编码必须唯一，该编码：" +code+ "已存在！");
            }
            String departmentName = jsonObj.getString("departmentName");
            if(StringUtils.isEmpty(departmentName)){
                throw new BusinessException("第" + (i+1) +  "行名称不能为空！");
            }
            JsonResult isOnlyName = userClient.isOnlyName(departmentName, null,companyJsonResult.getData().getId());
            if("false".equals(isOnlyName.getData().toString())){
                throw new BusinessException("第" + (i+1) +"行名称必须唯一，该名称：" +departmentName+ "已存在！");
            }
            //是否启用
            String isDeleted = jsonObj.getString("isDeleted");
            if(StringUtils.isEmpty(isDeleted)){
                throw new BusinessException("第" + (i+1) +"行是否启用不能为空！");
            }
            //是否终极部门
            String isFinal = jsonObj.getString("isFinal");
            if(StringUtils.isEmpty(isFinal)){
                throw new BusinessException("第" + (i+1) +"行是否终极部门不能为空！");
            }
            DepartmentForm departmentForm = new DepartmentForm();
            departmentForm.setCompanyInfoId(companyJsonResult.getData().getId())
                    .setParentId(departmentJsonResult==null?null:departmentJsonResult.getData().getId())
                    .setName(departmentName)
                    .setCode(code)
                    .setIsFinal(Boolean.parseBoolean(isFinal))
                    .setIsDeleted(Boolean.parseBoolean(isDeleted));
            JsonResult jsonResult = userClient.addDepartment(departmentForm);
            if (jsonResult.getCode() != Result.Code.SUCCESS.getCode()) {
                throw new BusinessException(jsonResult.getMsg());
            }

        }
    }
    public static void main(String[] args) {
        String desSign = DigestUtil.md5Hex("123456");
        String desSign2= DigestUtil.md5Hex("companyName" +"departmentName"+"code"+"postName" + desSign);
        System.out.println(desSign);
        System.out.println(desSign2);
    }
}
